import { Icon } from "@iconify/react"
import { Button, Flex, Tag } from "antd"
import { FC, useCallback, useEffect, useMemo, useState } from "react"
import { useSelector } from "react-redux"

import { queryBasicInfo, queryGetRiskControlNote } from "@/api/member"
import { IUserInfo } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { DataList } from "@/components/common"
import { Toast } from "@/components/messages"
import { usePagination } from "@/hooks"
import { UserState } from "@/interface/user/user"
import { FormatMessageProps, useLocale } from "@/locales"

import { MemberDetailModal } from "./components/MemberDetailModal"
import { ActionsContainer, BasicInfoContainer, ContentContainer } from "./styles"
import { columnsRemarks } from "./TableInfo"

export const getAccountStatusAndContent = (row: any, f: FormatMessageProps): { type: any; text: string }[] => {
	const statusTags = []
	if (!row?.loginLockStatus && !row?.paymentLockStatus && !row?.gameLockStatus) {
		statusTags.push({
			type: "success",
			text: f({ id: "common.account_status_normal" })
		})
	}

	if (row?.gameLockStatus === 1) {
		statusTags.push({
			type: "processing",
			text: f({ id: "common.game_lock_status" })
		})
	}

	if (row?.paymentLockStatus === 1) {
		statusTags.push({
			type: "warning",
			text: f({ id: "common.account_lock_status" })
		})
	}

	if (row?.loginLockStatus === 1) {
		statusTags.push({
			type: "error",
			text: f({ id: "common.login_lock_status" })
		})
	}
	return statusTags
}

interface IButtonPermission {
	visible: boolean
	disableKey?: number
}

const useGetButtonsPermission = () => {
	const permission = useSelector((state: { user: UserState }) => state.user.permissions) || []
	const defaultPermission = {
		riskControlLevel: { visible: false },
		labelMember: { visible: false, disableKey: 6 },
		rebateStatus: { visible: false, disableKey: 11 },
		riskControlNote: { visible: false, disableKey: 12 }
	}
	permission.forEach((per: string) => {
		if (per === "101034") defaultPermission.riskControlLevel.visible = true
		if (per === "101035") defaultPermission.labelMember.visible = true
		// if (per === "90810052") defaultPermission.rebateStatus.visible = true
		// if (per === "90810053") defaultPermission.riskControlNote.visible = true
		defaultPermission.rebateStatus.visible = true
		defaultPermission.riskControlNote.visible = true
	})
	return defaultPermission as Record<string, IButtonPermission>
}

export const RiskControl: FC<{
	data: IMemberParams
}> = ({ data }) => {
	const [userInfo, setUserInfo] = useState<IUserInfo | null>(null)
	const [dataRemark] = useState<any>({})
	const { formatMessage, newFormat } = useLocale()
	const buttonPermissions = useGetButtonsPermission()
	let totalPage = 0
	const auditList = useMemo(() => {
		if (userInfo)
			return userInfo.auditList.map(ele => {
				return ele.applyType
			})
		return []
	}, [userInfo])

	const [modalValue, setModalValue] = useState<any>(null)

	const { pagination, onPageChange } = usePagination(100)
	const handleGetUserInfo = useCallback(async () => {
		const tempParam = {
			...(data.merchantId ? { merchantId: data.merchantId } : {}),
			...(data.realName ? { realName: data.realName } : {}),
			...(data.mail ? { mail: data.mail } : {}),
			...(data.phoneNumber ? { phoneNo: `${data.phoneNoPrefix}-${data.phoneNumber}` } : {}),
			...(data.userName ? { userName: data.userName } : {})
		}

		const [err, basicInfoRes] = await queryBasicInfo(tempParam)
		const [, data1] = await queryGetRiskControlNote({
			pageNum: 1,
			pageSize: 100,
			userId: basicInfoRes.id
		})
		data.riskControlNote = data1.record
		totalPage = data1.totalPage
		if (err) Toast.error(err.msg)
		setUserInfo(basicInfoRes)
	}, [data, pagination])

	useEffect(() => {
		if (data.userId) handleGetUserInfo()
	}, [pagination])

	useEffect(() => {
		// this will help to refresh pagination when upper actions are changed
		if (data.userId) handleGetUserInfo()
	}, [data])

	useEffect(() => {
		handleGetUserInfo()
	}, [])

	const handleCancel = () => {
		setModalValue(null)
		handleGetUserInfo()
	}

	return (
		<BasicInfoContainer>
			<ActionsContainer>
				<Button>{newFormat("member.tabs.risk_control_info")}</Button>
				<Button
					type="primary"
					onClick={() => {
						handleGetUserInfo()
					}}
					icon={<Icon icon="solar:refresh-outline" fontSize="1.2rem" />}
				>
					{formatMessage({ id: "member.refresh" })}
				</Button>
				<div className="edit-title">
					<Icon icon="la:edit-solid" fontSize="1.2rem" />
					<span>{formatMessage({ id: "label.edit" })}</span>
				</div>
				<Flex gap={10} wrap="wrap">
					{Object.entries(buttonPermissions)
						.filter(([, value]) => value.visible)
						.map(([key, value]) => {
							const mess = `member.button_permissions.${key}`
							const title = newFormat(mess)
							const disable = value.disableKey ? auditList.includes(value.disableKey) : false
							return (
								<Button
									type="primary"
									key={key}
									disabled={disable}
									onClick={() => {
										if (!disable) setModalValue(key)
									}}
								>
									{title}
								</Button>
							)
						})}
				</Flex>
				{/* MODAL */}
				{userInfo && (
					<MemberDetailModal
						handleGetUserInfo={handleGetUserInfo}
						userInfo={userInfo}
						filterInfo={data}
						handleCancel={handleCancel}
						type={modalValue}
					/>
				)}
			</ActionsContainer>
			<ContentContainer>
				<h2>{formatMessage({ id: "member.summary_info" })}</h2>
				<div>
					<div className="content-item">
						<span>{newFormat("member.user_info.risk_control_level")}:</span>
						<span>{userInfo?.windControlName || "-"}</span>
					</div>
					<div className="content-item">
						<span>{newFormat("member.user_info.member_tag")}:</span>
						{auditList.includes(6) ? (
							<span style={{ color: "#E6A23C" }}>{formatMessage({ id: "member.user_info.under_review" })}</span>
						) : (
							<span>{userInfo?.labelName || "-"}</span>
						)}
					</div>
				</div>
				<div>
					<div className="content-item">
						<span>{newFormat("risk.rebate_status")}:</span>
						{userInfo?.rebateFreezeStatus === 0 && (
							<span>
								<Tag color="success" key={newFormat("common.account_status_normal")}>
									{newFormat("common.account_status_normal")}
								</Tag>
							</span>
						)}
						{userInfo?.rebateFreezeStatus === 1 && (
							<span>
								<Tag color="error" key={newFormat("risk.frozen_status")}>
									{newFormat("risk.frozen_status")}
								</Tag>
							</span>
						)}
					</div>
					<div className="content-item">
						<span>{newFormat("member.button_permissions.riskControlNote")}:</span>
						<span>{data.riskControlNote ? data.riskControlNote[0]?.note : "-"}</span>
					</div>
				</div>
			</ContentContainer>
			<DataList
				data={data.riskControlNote}
				rowKey="id"
				pagination={{
					pageSize: dataRemark.pageSize,
					current: dataRemark.pageNum,
					total: totalPage,
					showTotal: (total: number) => `共 ${total} 条`
				}}
				bordered
				columns={columnsRemarks(formatMessage, pagination)}
				size="middle"
				onChange={onPageChange}
			/>
		</BasicInfoContainer>
	)
}
